package com.bbg.amyam.process.jms.queue;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bbg.amyam.domain.model.PasswordRetrieveKey;
import com.bbg.amyam.domain.model.Profile;
import com.bbg.amyam.domain.model.School;
import com.bbg.amyam.web.mvc.cachemanager.SchoolCacheManager;
import com.bbg.amyam.web.mvc.exception.NoSchoolFoundException;
import com.bbg.amyam.web.util.StringEncryptor;

public class PasswordResetMessageHandler extends QueueMessageHandler {
	private static Log log = LogFactory
			.getLog(PasswordResetMessageHandler.class);

	@Override
	void handle(Object message) {
		if (message instanceof PasswordResetMessage) {
			sendEmail((PasswordResetMessage) message);
		}
	}

	private void sendEmail(PasswordResetMessage message) {
		String shortName = message.getSchoolShortName();
		long profileId = message.getProfileId();
		String requestURL = message.getRequestURL();

		try {
			Profile profile = Profile.findProfile(profileId);
			School school = SchoolCacheManager.getSchool(shortName);

			PasswordRetrieveKey key = new PasswordRetrieveKey();
			Date current = new Date();
			String retrieveKey = StringEncryptor.encrypte(String
					.valueOf(current));
			key.setCreatedDate(current);
			key.setProfileId(profile.getId());
			key.setRetrieveKey(retrieveKey);
			key.persist();

			String toEmailAddresses = profile.getEmail();
			String fromEmailAddress = "support@amyam.com";
			String subject = "Password reset notification from "
					+ school.getFullName();
			String templateFileName = "email_template/reset_profile_password.htm";

			String retriveveLink = requestURL + "/" + school.getShortName()
					+ "/school_public_view/retrieve_password?rk=" + retrieveKey;

			Map<String, Object> detail = new HashMap<String, Object>();
			detail.put("name",
					profile.getFirstName() + "," + profile.getLastName());
			detail.put("school_full_name", school.getFullName());
			detail.put("password_retrieve_link", retriveveLink);

			this.notificationService.sendEmail(toEmailAddresses,
					fromEmailAddress, subject, detail, templateFileName);
		} catch (NoSchoolFoundException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}

}
